<template>
  <div ref="wrap" class="chat-content" v-loading="isLoading">
    <MessageArea
      :isLoading="isLoading"
      :title="`留言板`"
      :subtitle="`${data.total}`"
      :list="data.rows"
      @submit="handleSubmit"
    />
  </div>
</template>

<script>
import MessageArea from "@/components/MessageArea";
import { getMessages, postMessage } from "@/api/message.js";
import fetchData from "@/mixins/fetchData";
import handleScroll from "@/mixins/handleScroll.js";
export default {
  mixins: [fetchData({ total: 0, rows: [] }), handleScroll("wrap")],
  data() {
    return {
      page: 1,
      limit: 10,
    };
  },
  components: {
    MessageArea,
  },
  created() {
    this.$bus.$on("mainScroll", this.handleScrollMore);
  },
  beforeDestroy() {
    this.$bus.$off("mainScroll", this.handleScrollMore);
  },
  methods: {
    async fetchData() {
      return await getMessages(this.page, this.limit);
    },
    async fetchMore() {
      this.page++;
      return await getMessages(this.page, this.limit);
    },
    async handleSubmit(info, callback) {
      let msg = await postMessage(info);
      this.data.rows.unshift(msg);
      this.data.total++;
      callback("提交成功");
      return;
    },
    async handleScrollMore(dom) {
      console.log(dom);
      if (!this.isLoading) {
        return;
      }
      if (!dom) {
        return;
      }
      if (this.hasBottom(dom)) {
        this.isLoading = false;
        let data = await this.fetchMore();
        this.data.total = data.total;
        this.data.rows = this.data.rows.concat(data.rows);
        this.isLoading = true;
      }
    },
    hasBottom(dom) {
      // 判断是否到了底部
      const boundary = 100;
      const desc = Math.abs(
        dom.scrollHeight - (dom.scrollTop + dom.clientHeight)
      );
      return desc <= boundary;
    },
  },
};
</script>

<style lang="less" scoped>
.chat-content {
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  position: relative;
  overflow-x: hidden;
  overflow-y: scroll;
  scroll-behavior: smooth;
}
.MessageArea-content {
  width: 700px;
  margin: 0 auto;
}
</style>